package com.siwei.mes.common.exception.handler;

import com.siwei.mes.common.exception.BizException;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.MessageSource;

import java.util.Locale;
import java.util.Optional;

/**
 * @Description: 消息处理
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2021-12-08
 */

@Getter
public class MessageHandler {
    public final static String NORMAL_EXCEPTION = "10000:网络不给力";
    public final static String SPERATOR = ":";

    @Setter
    private MessageSource messageSource;

    private final static MessageHandler HANDLER = new Singleton<>(MessageHandler::new).get();


    public static void assertTrue(String message) throws BizException {
        String[] error = Optional.of(getMessage(message)).filter(e -> e.length == 2).orElseGet(() -> NORMAL_EXCEPTION.split(SPERATOR));
        throw new BizException(error[0], error[1]);
    }

    public static void assertTrue(boolean expression, String message) throws BizException {
        if (expression) {
            String[] error = Optional.of(getMessage(message)).filter(e -> e.length == 2).orElseGet(() -> NORMAL_EXCEPTION.split(SPERATOR));
            throw new BizException(error[0], error[1]);
        }
    }

    public static void assertTrue(boolean expression, String message, Throwable cause) throws BizException {
        if (expression) {
            String[] error = Optional.of(getMessage(message)).filter(e -> e.length == 2).orElseGet(() -> NORMAL_EXCEPTION.split(SPERATOR));
            throw new BizException(cause, error[0], error[1]);
        }
    }

    public static String[] getMessage(String message) {
        try {
            Optional<String> optional = Optional.of(HANDLER.getMessageSource().getMessage(message, null, Locale.CHINA));
            return optional.map(msg -> msg.split(SPERATOR)).get();
        } catch (Exception e) {
            return new String[]{"-1", message};
        }
    }

    public static MessageHandler of(MessageSource messageSource) {
        HANDLER.setMessageSource(messageSource);
        return HANDLER;
    }
}
